<?php
// Oss 上传服务


namespace app\common\service;

class Oss
{
    private $ossClient = null;
    private $bucket = '';

    public function __construct()
    {
        $ossConfig = config('UPLOAD_OSS_CONFIG');
        try {
            $this->ossClient = new \OSS\OssClient($ossConfig['AccessKeyId'], $ossConfig['AccessKeySecret'], $ossConfig['Endpoint']);
        } catch (\OSS\OssException $exception) {
            die($exception->getMessage());
        }
        $this->bucket = $ossConfig['Bucket'];
    }

    /**
     * 上传文件
     * @param string $source_path 源文件地址
     * @param bool $delete_source_file 是否删除源文件，默认删除 true 删除，false 不删除
     * @return array 返回上传结果
     * @throws \OSS\Core\OssException
     */
    public function uploadFile($source_path, $delete_source_file=true){

        $ext = pathinfo($source_path, PATHINFO_EXTENSION);
        $oss_path = date('Y/m/d/') . md5($source_path . THINK_START_TIME) . rand(1000, 9999) . '.' . $ext;
        $res = $this->ossClient->uploadFile($this->bucket, $oss_path, $source_path);
        if ($delete_source_file) {
            unlink($source_path);
        }
        if ($res === null) {
            $code = -1;
            $msg = 'OSS上传失败';
            $data = [];
        } else {
            $code = 1;
            $msg = 'OSS上传成功';
            $data = [
                'oss_path' => $oss_path,
                'size' => $res['info']['size_upload'],
            ];
        }
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
    }

    /**
     * 删除文件
     * @param array|string $oss_path 单个文件地址或多个文件地址的数组
     * @return array 删除结果
     */
    public function deleteFile($oss_path)
    {
        if (is_array($oss_path)) {
            $this->ossClient->deleteObjects($this->bucket, $oss_path);
        } else {
            $this->ossClient->deleteObject($this->bucket, $oss_path);
        }
        $code = 1;
        $msg = 'OSS删除成功';
        $data = [];

        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
    }
}